﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcLibrary.Repository;
using System.IO;
using WebVideo.Areas.Admin.Models;
using System.Data.Linq.SqlClient;
namespace WebVideo.Areas.Admin.Controllers
{
    public class Questions_MultipleChoiceController : Controller
    {
        //
        // GET: /Admin/Questions_MultipleChoice/

        public ActionResult Index(int Id)
        {
            ViewBag.IdVideo = Id;
            return View(Questions_MultipleChoiceModel.LayDuLieu(Id));
        }
        #region "Insert"
        public ActionResult Insert(int IdVideo)
        {
            Questions_MultipleChoiceModel tnew = new Questions_MultipleChoiceModel();
            if (IdVideo > 0)
            {
                tnew.IdVideo = IdVideo;
            }

            return View(tnew);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Insert(Questions_MultipleChoiceModel Mtnew, HttpPostedFileBase Image)
        {

            try
            {
                if (Image != null && Image.ContentLength > 0)
                {
                    int kb = Image.ContentLength / 1024; //file size kb
                    if (kb >= 2048) // file qua lon
                    {
                        return RedirectToAction("Index", "Error", new { errorMsg = "Hình ảnh phải bé hơn 2MB." });
                    }
                    ImageHelper imgHelper = new ImageHelper();
                    string encodestring = imgHelper.encodeImageFile(Image);

                    if (encodestring == "!")
                        return RedirectToAction("Index", "Error", new { errorMsg = "Không thể Upload hình" });

                    var path = Path.Combine(Server.MapPath("~/Content/Images/Video"), encodestring);
                    Image.SaveAs(path);

                    Mtnew.Image = encodestring;
                }
                    Questions_MultipleChoiceModel.Insert(Mtnew);
                    dbVideoDataContext db = new dbVideoDataContext();
                    if (Mtnew.IdVideo != 0)
                    {
                        if (db.EntityVideos.Where(g => g.Id == Mtnew.IdVideo).First().TypeQuestion == 1)
                        {
                            return RedirectToAction("Index", "Questions_Essay", new { Id = Mtnew.IdVideo });
                        }
                        return RedirectToAction("Index", "Questions_MultipleChoice", new { Id = Mtnew.IdVideo });
                    }
                    return RedirectToAction("ListImage", "Questions_MultipleChoice");
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }
           
        }
        #endregion //insert

        #region "Insert câu hỏi trắc ngiệm video có thể loại câu hỏi là tự luận"
        public ActionResult Insert1(int IdVideo)
        {
            Questions_MultipleChoiceModel tnew = new Questions_MultipleChoiceModel();
            tnew.IdVideo = IdVideo;
            return View(tnew);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Insert1(Questions_MultipleChoiceModel Mtnew, HttpPostedFileBase Image)
        {

            try
            {
                if (Image != null && Image.ContentLength > 0)
                {
                    int kb = Image.ContentLength / 1024; //file size kb
                    if (kb >= 2048) // file qua lon
                    {
                        return RedirectToAction("Index", "Error", new { errorMsg = "Hình ảnh phải bé hơn 2MB." });
                    }
                    ImageHelper imgHelper = new ImageHelper();
                    string encodestring = imgHelper.encodeImageFile(Image);

                    if (encodestring == "!")
                        return RedirectToAction("Index", "Error", new { errorMsg = "Không thể Upload hình" });

                    var path = Path.Combine(Server.MapPath("~/Content/Images/Video"), encodestring);
                    Image.SaveAs(path);

                    Mtnew.Image = encodestring;
                }
                Questions_MultipleChoiceModel.Insert(Mtnew);
                dbVideoDataContext db = new dbVideoDataContext();
                if (db.EntityVideos.Where(g => g.Id == Mtnew.IdVideo).First().TypeQuestion == 1)
                {
                    return RedirectToAction("Index", "Questions_Essay", new { Id = Mtnew.IdVideo });
                }
                return RedirectToAction("Index", "Questions_MultipleChoice", new { Id = Mtnew.IdVideo });
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }

        }
        #endregion //insert
        #region "Edit"
        public ActionResult Edit(int IdQVideo)
        {
            Questions_MultipleChoiceModel x = Questions_MultipleChoiceModel.LayModel(IdQVideo);
            ViewBag.IdVideo = x.IdVideo;
            return View(x);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(Questions_MultipleChoiceModel Mtnew, HttpPostedFileBase Image)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    if (Image != null && Image.ContentLength > 0)
                    {
                        int kb = Image.ContentLength / 1024; //file size kb
                        if (kb >= 2048) // file qua lon
                        {
                            return RedirectToAction("Index", "Error", new { errorMsg = "Hình ảnh phải bé hơn 2MB." });
                        }
                        ImageHelper imgHelper = new ImageHelper();
                        string encodestring = imgHelper.encodeImageFile(Image);

                        if (encodestring == "!")
                            return RedirectToAction("Index", "Error", new { errorMsg = "Không thể Upload hình" });

                        var path = Path.Combine(Server.MapPath("~/Content/Images/Video"), encodestring);
                        Image.SaveAs(path);

                        Mtnew.Image = encodestring;
                    }

                    string HinhAnh = Questions_MultipleChoiceModel.Edit(Mtnew);
                    if (HinhAnh != null)
                    {
                        string fileToDelete = Path.Combine(Server.MapPath("~/Content/Images/Video"), HinhAnh); // file hinh cu
                        System.IO.File.Delete(fileToDelete);
                    }

                    dbVideoDataContext db = new dbVideoDataContext();
                    if (db.EntityVideos.Where(g => g.Id == Mtnew.IdVideo).First().TypeQuestion == 1)
                    {
                        return RedirectToAction("Index", "Questions_Essay", new { Id = Mtnew.IdVideo });
                    }
                    return RedirectToAction("Index", "Questions_MultipleChoice", new { Id = Mtnew.IdVideo });
                }
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }
            return View(Mtnew);
        }
        #endregion //Edit

        #region "Delete"

        public string Delete(int Id)
        {
            try
            {
              

                string image = Questions_MultipleChoiceModel.Delete(Id);
                if (image != null)
                {
                    string fileToDelete = Path.Combine(Server.MapPath("~/Content/Images/Video"), image); // file hinh cu
                    System.IO.File.Delete(fileToDelete);
                }
              
                return "ok";

            }
            catch
            {
                return "error";

            }

        }

        #endregion //Delete



        #region "Danh sách câu hỏi dành cho hình ảnh"
        public ActionResult ListImage()
        {
            dbVideoDataContext db = new dbVideoDataContext();
            return View(db.EntityQuestions_MultipleChoices.Where(g=>g.Type == 1).ToList());
        }
        #endregion

        #region "Danh sách câu hỏi dành cho hình ảnh, để user chọn"
        public ActionResult ListImageAdmin(int IdVideo)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            var likestr = string.Format("%{0}%", IdVideo.ToString()+",");
            ViewBag.IdVideo = IdVideo;
            var query = from p in db.EntityQuestions_MultipleChoices
                        where !(from o in db.EntityQuestions_MultipleChoices where SqlMethods.Like(o.ListVideo, likestr) select o.Id).Contains(p.Id)
                        select p;

            return View(query.Where(g=>g.Type == 1).ToList());
        }
        #endregion

        public ActionResult TracNgiemHinhAnh(int IdVideo)
        {
            dbVideoDataContext db = new dbVideoDataContext();
            var likestr = string.Format("%{0}%", IdVideo.ToString() + ",");
            ViewBag.IdVideo = IdVideo;
            var query = from p in db.EntityQuestions_MultipleChoices
                        where SqlMethods.Like(p.ListVideo, likestr)
                        select p;

            return PartialView(query.Where(g => g.Type == 1).ToList());
        }
        #region "Xóa câu hỏi ra khỏi video"

        public string DeleteImage(int Id, int IdVideo)
        {
            try
            {
                dbVideoDataContext db = new dbVideoDataContext();

                var likestr = string.Format("%{0}%", IdVideo.ToString() + ",");
                var query = from p in db.EntityQuestions_MultipleChoices
                            where SqlMethods.Like(p.ListVideo, likestr)
                            select p;
                if (query.ToList().Count() > 1)
                {
                    EntityQuestions_MultipleChoice q = db.EntityQuestions_MultipleChoices.Where(g => g.Id == Id).First();
                    string c = q.ListVideo.ToString();
                    string[] arr = c.Split(',');
                    c = "";
                    foreach (var item in arr)
                    {
                        if (item.ToString() != IdVideo.ToString() && item.ToString() != "" && item.ToString() != null)
                            c = c + item.ToString() + ",";
                    }

                    q.ListVideo = c;
                    db.SubmitChanges();
                    return "Complete";
                }
                else
                {
                    return "error";
                }
            }
            catch
            {
                return "error";
            }
        }
        #endregion
        #region "Thêm câu hỏi cho video"
        public string  ChonImage(int Id, int IdVideo)
        {
            try
            {
                dbVideoDataContext db = new dbVideoDataContext();
                EntityQuestions_MultipleChoice q = db.EntityQuestions_MultipleChoices.Where(g => g.Id == Id).First();
                string c = q.ListVideo + IdVideo.ToString() + ",";
                q.ListVideo = c;
                db.SubmitChanges();
                return "Complete";
            }
            catch
            {
                return "error";
            }
        }
        #endregion

    }
}